/**
 * DRW(Direct Web Remoting) JSON Data Loader - jQuery Extension
 * 
 * Copyright (c) 2009-2013 Rime Lee. All rights reserved.
 */
(function($) {
	$.jsonloader = function(container, options) {
		if (!options.url) {
			return false;
		}
		if (options.onBeforeLoad.call(container, options.queryParams) == false) {
			return false;
		}
		if (!options.method) {
			options.method = "GET";
		}
		$.ajax({
			beforeSend : function() {
				$("<div class='panel-loading'>加载中...</div>")
						.appendTo(container);
			},
			type : options.method,
			url : options.url,
			data : options.queryParams,
			dataType : 'json',
			error : function(xhr, status) {
				$(container).children(".panel-loading").remove();
				options.onLoadError.apply(container, arguments);
			},
			success : function(data) {
				$(container).children(".panel-loading").remove();
				options.loadData.call(container, data);
			}
		});
		return true;
	};

	$.jsonloader.defaults = {
		url : null,
		queryParams : null,
		loadData : function(data) {
		},
		onBeforeLoad : function(param) {
			return true;
		},
		onLoadError : function(xhr, status) {
			var e = JSON.parse(xhr.responseText);
			if (e.name == "AccessDeniedException") {
				alert("当前用户权限执行此操作");
			} else if (e.name == "JsonException") {
				alert(e.message);
			} else {
				alert(e.message + "[" + e.name + "]");
			}
		}
	};
})(jQuery);